package com.sh.shanhuo.activity;

import android.os.Handler;
import android.widget.EditText;
import android.widget.Toast;

import com.sh.shanhuo.R;
import com.sh.shanhuo.bean.BaseBean;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class ForgetPasswordActivity extends BaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_forget_password;
    }

    @Override
    protected void initData() {
        super.initData();
        findViewById(R.id.back).setOnClickListener(v ->
                ScreenSwitch.finish(ForgetPasswordActivity.this));
        EditText email = findViewById(R.id.email);
        EditText account = findViewById(R.id.account);
        findViewById(R.id.resetPassword).setOnClickListener(v -> {
            if (account.getText().toString().length() == 0) {
                Toast.makeText(ForgetPasswordActivity.this, "账号不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (email.getText().toString().length() == 0) {
                Toast.makeText(ForgetPasswordActivity.this, "邮箱不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            reset(account.getText().toString().trim(), email.getText().toString().trim());
        });
    }

    private void reset(String account, String email) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", account);
        params.put("email", email);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.RESET_PASSWORD, params,
                new GsonObjectCallback<BaseBean>() {
                    @Override
                    public void onUi(BaseBean baseBean) {
                        if (baseBean.getCode() == 200 && "操作成功".equals(baseBean.getMsg())) {
                            Toast.makeText(ForgetPasswordActivity.this,
                                    "邮件发送成功，请打开邮箱查看密码", Toast.LENGTH_SHORT).show();
                            handler.sendEmptyMessageDelayed(100, 2000);
                        } else {
                            Toast.makeText(ForgetPasswordActivity.this, "邮件发送失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailed(Call call, IOException e) {
                        Toast.makeText(ForgetPasswordActivity.this, "邮件发送失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private final Handler handler = new Handler(msg -> {
        if (msg.what == 100) {
            ScreenSwitch.finish(ForgetPasswordActivity.this);
        }
        return false;
    });
}
